import { withRouter } from 'react-router-dom'
import { useEffect, useState } from 'react';
import { Form, Input, Button, Result } from 'antd';
import Layout from '../../components/layout'
import $http from '../../utils/require';
import rules from '../../utils/rules'
import React from 'react';
import { Res, WithRouteProps } from '../../types/base';
import stores from '../../stores';


const SignUp = (props: WithRouteProps) => {
    console.log('SignUp', props);


    let [result, setResult]: [Res, Function] = useState({})
    let [form] = Form.useForm()


    let useRes = (resObj: any) => {
        let status: 'success' | 'warning';
        let title: string;
        let extra: [] | [any];

        if ((Object.keys(resObj).length === 0) || !resObj) return <></>

        if (resObj.error) {
            status = 'warning';
            title = resObj.error;
            extra = [];
        } else {
            status = 'success'
            title = '注册成功'
            extra = [<Button type="primary" onClick={signIn} key="1">登录</Button>]
        }

        return <Result
            status={status}
            title={title}
            extra={extra}
        />
    }

    const signIn = () => {
        let { email, password } = form.getFieldsValue()

        $http['signin']({
            email,
            password
        }).then(res => {
            stores.User.setLocalInfo(res)
            setResult({})
            form.resetFields()
            props.history.push(res.user.role === 1 ? '/admin/dashboard' : '/user/dashboard')
        }).catch(err => {
            // setResult(err)
        })
    }

    const onFinish = (values: any) => {
        console.log('Success:', values);
        $http['signup'](values).then(res => {
            setResult(res)
        }).catch(err => {
            setResult(err)
        })
    };
    return (
        <Layout title="注册" subtitle="赶紧注册你的专属账号吧">
            {useRes(result)}
            {

                <Form form={form} onFinish={onFinish} style={{
                    height: (Object.keys(result).length === 0 || result.error) ? 'auto' : 0,
                    overflow: 'hidden'
                }}>
                    <Form.Item name="name" label="昵称" rules={rules.name}>
                        <Input></Input>
                    </Form.Item>
                    <Form.Item name="password" label="密码" rules={rules.password}>
                        <Input.Password></Input.Password>
                    </Form.Item>
                    <Form.Item name="email" label="邮箱" rules={rules.email}>
                        <Input></Input>
                    </Form.Item>
                    <Button type="primary" htmlType="submit">注册</Button>
                </Form>
            }

        </Layout>
    )
}

export default withRouter(SignUp)
